import Vue from "vue";
import VueRouter from "vue-router";
import Home from "@/views/home/index.vue";
import Layout from "@/layout/index.vue";
import NotFound from "@/views/404/404.vue";
import Article from "@/views/article/index.vue";
import Archive from "@/views/archives/index.vue";
import Categories from "@/views/categories/index.vue";
import Tags from "@/views/tags/index.vue";
import Messages from "@/views/messages/index.vue";
import About from "@/views/about/index.vue";
import Photos from "@/views/photos/index.vue";
import store from "@/store";

Vue.use(VueRouter);

// 统一的加载文本
const commonLoadingTexts = ["加载中...", "加载完毕!"];

// 路由与加载目标类型的映射
const routeLoadingTargets = {
  "/": "home",
  "/post": "post",
  "/moments": "moments",
  "/photos": "photos",
  "/archive": "archive",
  "/categories": "categories",
  "/tags": "tags",
  "/messages": "messages",
  "/about": "about",
  "/hotSearch": "hotSearch",
  "/resources": "resources",
  "/friends": "friends",
  "/user/profile": "profile",
  "/editor": "editor",
  "/chat": "chat",
  "/im": "chat",
  "/im/chat": "chat",
  "/im/friend": "chat",
  "/im/group": "chat",
  "/login": "login",
  "/moments/:id": "momentDetail",
  "/user/:userId": "userProfile",
};

// 特殊路由的处理函数
const getLoadingTarget = (path) => {
  // 处理文章详情页
  if (path.startsWith("/post/")) {
    return "post";
  }

  // 处理相册详情页
  if (path.match(/^\/photos\/\d+$/)) {
    return "photos";
  }

  // 处理说说详情页
  if (path.startsWith("/moments/")) {
    return "momentDetail";
  }

  // 处理用户主页
  if (path.startsWith("/user/")) {
    if (path.includes("/profile")) {
      return "profile";
    }
    return "userProfile";
  }

  // 查找匹配的路由
  const route = Object.keys(routeLoadingTargets).find((route) =>
    path.startsWith(route)
  );
  return route ? routeLoadingTargets[route] : "default";
};

const routes = [
  {
    path: "/",
    component: Layout,
    meta: {
      title: "🎯 KingCola-ICG Blog | 始于代码，不止于代码 ",
      loading: true,
    },
    children: [
      {
        path: "/",
        name: "Home",
        component: Home,
        meta: {
          title: "首页",
          transition: "fade",
          icon: "fas fa-home",
          loading: true,
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/archive",
        name: "Archive",
        component: Archive,
        meta: {
          transition: "fade",
          title: "归档 - KingCola-ICG Blog",
          icon: "fas fa-archive",
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/categories",
        name: "Categories",
        component: Categories,
        meta: {
          transition: "fade",
          title: "分类 - KingCola-ICG Blog",
          icon: "fas fa-folder",
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/tags",
        name: "Tags",
        component: Tags,
        meta: {
          transition: "fade",
          title: "标签 - KingCola-ICG Blog",
          icon: "fas fa-tags",
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/moments",
        name: "Moments",
        component: () => import("@/views/moments/index.vue"),
        meta: {
          title: "说说 - KingCola-ICG Blog",
          icon: "fas fa-comment-dots",
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/moments/:id",
        name: "MomentDetail",
        component: () => import("@/views/moments/detail.vue"),
        meta: {
          title: "说说详情 - KingCola-ICG Blog",
          hidden: true,
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/photos",
        name: "Photos",
        component: Photos,
        meta: {
          transition: "fade",
          title: "相册 - KingCola-ICG Blog",
          icon: "fas fa-images",
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/photos/:id",
        name: "PhotoDetail",
        component: () => import("@/views/photos/detail.vue"),
        meta: {
          transition: "fade",
          title: "相册详情 - KingCola-ICG Blog",
          icon: "fas fa-images",
          hidden: true,
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/hotSearch",
        name: "HotSearch",
        component: () =>
          import(/* webpackPrefetch: true */ "@/views/hotSearch/index.vue"),
        meta: {
          transition: "fade",
          title: "热搜 - KingCola-ICG Blog",
          icon: "fas fa-fire",
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/resources",
        name: "Resources",
        component: () => import("@/views/resources/index.vue"),
        meta: {
          title: "资源",
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/messages",
        name: "Messages",
        component: Messages,
        meta: {
          transition: "fade",
          title: "留言板 - KingCola-ICG Blog",
          icon: "fas fa-comments",
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/friends",
        name: "Friends",
        component: () =>
          import(/* webpackPrefetch: true */ "@/views/friends/index.vue"),
        meta: {
          transition: "fade",
          title: "友情链接 - KingCola-ICG Blog",
          icon: "fas fa-user-friends",
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/about",
        name: "About",
        component: About,
        meta: {
          transition: "fade",
          title: "关于本站 - KingCola-ICG Blog",
          icon: "fas fa-info-circle",
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/post/:id",
        name: "Post",
        component: Article,
        props: true,
        meta: {
          hidden: true,
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/user/profile",
        name: "Profile",
        component: () =>
          import(/* webpackPrefetch: true */ "@/views/profile/index.vue"),
        meta: {
          title: "个人主页 - KingCola-ICG Blog",
          icon: "fas fa-user",
          hidden: true,
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/user/:userId",
        name: "UserProfile",
        component: () => import("@/views/user/index.vue"),
        meta: {
          title: "用户主页 - KingCola-ICG Blog",
          hidden: true,
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/editor",
        name: "Editor",
        component: () =>
          import(/* webpackPrefetch: true */ "@/views/editor/index-new.vue"),
        meta: {
          title: "写文章 - KingCola-ICG Blog",
          icon: "fas fa-edit",
          requireAuth: true,
          hidden: true,
          loadingTexts: commonLoadingTexts,
        },
      },
      // {
      //   path: "/chat",
      //   name: "Chat",
      //   component: () =>
      //     import(/* webpackPrefetch: true */ "@/views/chat/index.vue"),
      //   meta: {
      //     title: "聊天 - KingCola-ICG Blog",
      //     icon: "fas fa-comments",
      //     hidden: true,
      //     loadingTexts: pageLoadingTexts.chat,
      //   },
      // },
      {
        path: "/im",
        name: "IMHome",
        component: () => import("@/views/im/home.vue"),
        redirect: "/im/chat",
        meta: {
          title: "即时通讯 - KingCola-ICG Blog",
          icon: "fas fa-comment-dots",
          hidden: false,
        },
        children: [
          {
            path: "chat",
            name: "IMChat",
            component: () => import("@/views/im/chat.vue"),
            meta: {
              title: "聊天",
              icon: "fas fa-comments",
              loading: false, // 禁用加载动画，保持WebSocket连接
            },
          },
          {
            path: "friend",
            name: "IMFriend",
            component: () => import("@/views/im/friend.vue"),
            meta: {
              title: "好友",
              icon: "fas fa-user-friends",
              loading: false, // 禁用加载动画，保持WebSocket连接
            },
          },
          {
            path: "group",
            name: "IMGroup",
            component: () => import("@/views/im/group.vue"),
            meta: {
              title: "群组",
              icon: "fas fa-users",
              loading: false, // 禁用加载动画，保持WebSocket连接
            },
          },
        ],
      },
      {
        path: "/login",
        name: "Login",
        component: () => import("@/views/login/index.vue"),
        meta: {
          title: "登录",
          hidden: true,
          fullscreen: true,
          loadingTexts: commonLoadingTexts,
        },
      },
      {
        path: "/:pathMatch(.*)*",
        name: "NotFound",
        component: NotFound,
        meta: {
          hidden: true,
          loadingTexts: commonLoadingTexts,
        },
      },
    ],
  },
];

const router = new VueRouter({
  mode: "history",
  base: "/",
  routes,
  scrollBehavior(to, from, savedPosition) {
    // IM路由之间切换时保持当前滚动位置，不要滚动到顶部
    const isIMRoute = to.path.startsWith('/im') && from.path.startsWith('/im');

    if (isIMRoute) {
      // IM路由之间切换时，保持当前滚动位置
      return false; // 返回false表示不改变滚动位置
    }

    // 如果有保存的滚动位置（如浏览器前进后退），使用保存的位置
    if (savedPosition) {
      return savedPosition;
    }

    // 其他情况滚动到顶部
    return { x: 0, y: 0 };
  },
});

// 解决重复点击导航时，控制台出现报错
const VueRouterPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(to) {
  return VueRouterPush.call(this, to).catch((err) => err);
};

router.beforeEach((to, from, next) => {
  console.log(`路由导航: ${from.path} -> ${to.path}`);

  // 检查IM路由的登录状态
  if (to.path.startsWith('/im')) {
    // 检查用户是否已登录
    if (!store.state.userInfo) {
      console.log('用户未登录，无法访问IM页面，跳转到登录页');
      next('/login?redirect=' + encodeURIComponent(to.fullPath));
      return;
    }
  }

  // 如果之前有加载状态，确保清除
  if (store.state.isLoading) {
    console.log("清除上一个路由的加载状态");
    store.commit("SET_LOADING", false);
    store.commit("SET_CONTENT_READY", false);
  }

  // 检查是否有开屏动画正在显示
  const splashScreenVisible =
    document.querySelector(".splash-screen") &&
    !document.querySelector(".splash-screen.fade-out");

  // IM路由切换特殊处理：完全跳过加载动画，实现平滑切换
  const isIMRoute = to.path.startsWith('/im/') && from.path.startsWith('/im/');
  const isIMParentRoute = to.path === '/im' || from.path === '/im';

  if (isIMRoute || isIMParentRoute) {
    console.log(`IM路由平滑切换: ${from.path} -> ${to.path}, 跳过加载动画`);
    // IM路由切换时完全跳过加载逻辑，保持WebSocket连接和组件状态
    // 直接继续路由导航，不触发任何加载状态
  } else if (!splashScreenVisible && to.meta && to.meta.loading !== false) {
    // 非IM路由的正常加载逻辑
    // 设置当前路由对应的加载文本
    if (to.meta.loadingTexts && to.meta.loadingTexts.length > 0) {
      // 临时存储加载文本到Vuex
      store.commit("SET_LOADING_TEXTS", to.meta.loadingTexts);
    }

    // 获取当前路由的加载目标类型
    const loadingTarget = getLoadingTarget(to.path);
    console.log(
      `路由切换: ${from.path} -> ${to.path}, 加载目标: ${loadingTarget}`
    );

    // 触发加载状态，传入目标类型
    store.dispatch("showLoading", loadingTarget);
  }

  // 基础标题（从环境变量获取或使用默认值）
  const baseTitle = "🎯 KingCola-ICG Blog | 始于代码，不止于代码";

  // 为不同页面设置个性化标题
  const pageTitles = {
    "/": "首页 | 探索技术与创意的交汇点",
    "/archive": "归档 | 时间线上的技术足迹",
    "/categories": "分类 | 知识体系的构建",
    "/tags": "标签 | 技术关键词导航",
    "/moments": "说说 | 团队的日常思考",
    "/photos": "相册 | 视觉记忆库",
    "/hotSearch": "热搜 | 技术圈热点聚焦",
    "/resources": "资源 | 精选工具与资料",
    "/messages": "留言板 | 与团队交流互动",
    "/friends": "友链 | 志同道合的伙伴",
    "/about": "关于 | 认识KingCola-ICG团队",
    "/user/profile": "个人主页 | 开发者档案",
    "/editor": "创作中心 | 分享你的技术见解",
    "/chat": "聊天 | 即时交流平台",
    "/im": "IM | 智能即时通讯系统",
    "/im/chat": "聊天 | 消息对话",
    "/im/friend": "好友 | 联系人管理",
    "/im/group": "群组 | 群聊管理",
    "/login": "登录 | 加入技术社区",
  };

  let finalTitle = "";

  // 处理特殊路由：文章详情页
  if (to.path.startsWith("/post/")) {
    // 尝试从vuex中获取当前文章标题
    const currentArticle = store.state.currentArticle;
    if (currentArticle && currentArticle.title) {
      finalTitle = `${currentArticle.title} | 技术文章`;
    } else {
      // 如果没有文章标题，先使用一个临时标题
      finalTitle = "文章详情 | 技术洞见";

      // 在组件中获取文章详情后，会更新标题
      // 这部分逻辑会在Article组件中实现
    }
  }
  // 处理说说详情页
  else if (to.path.startsWith("/moments/")) {
    finalTitle = "说说详情 | 记录此刻";
  }
  // 处理相册详情页
  else if (to.path.match(/^\/photos\/\d+$/)) {
    finalTitle = "相册详情 | 视觉记忆";
  }
  // 处理其他页面
  else {
    // 查找预定义的标题
    const matchedTitle = pageTitles[to.path];
    if (matchedTitle) {
      finalTitle = matchedTitle;
    }
    // 回退到路由元信息中的标题
    else if (to.meta && to.meta.title) {
      finalTitle = to.meta.title;
    }
    // 最后回退到路由名称
    else if (to.name) {
      finalTitle = to.name;
    }
  }

  // 设置最终的页面标题
  document.title = `${finalTitle} - ${baseTitle}`;

  // 如果是说说页面，检查登录状态
  if (to.path === "/moments") {
    console.log("进入说说页面，登录状态:", store.getters.isLogin);
  }

  // 关闭搜索框
  store.commit("SET_SEARCH_VISIBLE", false);

  next();
});

// 路由加载完成后处理
router.afterEach((to, from) => {
  console.log(`路由加载完成: ${to.path}`);

  // IM路由切换特殊处理：不需要任何加载状态处理
  const isIMRoute = to.path.startsWith('/im/') && from.path.startsWith('/im/');
  const isIMParentRoute = to.path === '/im' || from.path === '/im';

  if (isIMRoute || isIMParentRoute) {
    console.log(`IM路由切换完成: ${to.path}, 无需处理加载状态`);
    return; // 直接返回，不做任何加载状态处理
  }

  // 不再自动关闭加载状态，而是由内容组件通知加载完成
  // 只有某些不需要内容加载的路由会在这里关闭加载状态
  const simpleRoutes = ["/login", "/about"];

  if (simpleRoutes.includes(to.path)) {
    // 对于简单路由，延迟短暂时间后关闭加载状态
    console.log(`简单路由: ${to.path}, 自动关闭加载状态`);
    setTimeout(() => {
      if (store.state.isLoading) {
        store.dispatch("contentReady");
      }
    }, 300);
  } else {
    // 对于复杂路由，设置最大超时
    setTimeout(() => {
      if (store.state.isLoading) {
        console.log(`路由加载超时: ${to.path}, 强制关闭加载状态`);
        store.dispatch("contentReady");
      }
    }, 5000); // 5秒超时保障
  }
});

export default router;
